package com.hty.locusmap;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.CoordinateConverter;

public class HistoryLocus extends Activity {

	MapView mMapView = null;
	BaiduMap mBaiduMap;
	BitmapDescriptor mCurrentMarker;
	LocationMode mCurrentMode;
	BitmapDescriptor bitmap1, bitmap2, bitmap3;
	ImageButton imgbtn1;
	Button button1, button2;
	int num;
	boolean flag = true;
	String filepath = "", filename="";
	TextView textView_info;
	Track track;
	SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
	List<LatLng> list_photo_LatLng = new ArrayList<LatLng>();
	Marker marker1;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		MainApplication.getInstance().addActivity(this);
		SDKInitializer.initialize(getApplicationContext());
		setContentView(R.layout.activity_history);
		textView_info = findViewById(R.id.textView_info);
		imgbtn1 = (ImageButton) findViewById(R.id.imageButton_location);
		button1 = (Button) findViewById(R.id.button_map);
		button1.setOnClickListener(new MyOnClickListener());
		button2 = (Button) findViewById(R.id.button_history);
		button2.setOnClickListener(new MyOnClickListener());
		bitmap1 = BitmapDescriptorFactory.fromResource(R.drawable.start);
		bitmap2 = BitmapDescriptorFactory.fromResource(R.drawable.end);
		bitmap3 = BitmapDescriptorFactory.fromResource(R.drawable.blue);
		mCurrentMarker = null;
		mCurrentMode = LocationMode.NORMAL;
		mMapView = (MapView) findViewById(R.id.bmapView);
		mBaiduMap = mMapView.getMap();
		UiSettings settings = mBaiduMap.getUiSettings();
		settings.setRotateGesturesEnabled(false);
		settings.setOverlookingGesturesEnabled(false);
		mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().zoom(16).build()));
		mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker));
		mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
			@Override
			public boolean onMarkerClick(Marker marker) {
				Bundle extraInfo = marker.getExtraInfo();
				int index = extraInfo.getInt("index");
				String time = extraInfo.getString("time");
				String image_path = extraInfo.getString("image_path");
				ImageView imageView = new ImageView(HistoryLocus.this);
				Uri uri = Uri.fromFile(new File(image_path));
				imageView.setImageURI(uri);
				new AlertDialog.Builder(HistoryLocus.this).setTitle(index + ":" + time).setView(imageView).setPositiveButton("确定", null).show();
				//textView_info.setText(index + "\n经度：" + marker.getPosition().latitude + "\n纬度：" + marker.getPosition().longitude);
				marker1.setPosition(marker.getPosition());
				return false;
			}
		});
	}

	class MyOnClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.button_map:
				flag = false;
				// MyThread t = new MyThread();
				// t.start();
				new Thread(new MyThread()).start();
				break;
			case R.id.button_history:
				flag = true;
				// OverlayOptions option = new MarkerOptions().position(
				// points.get(MyThread.geti())).icon(bitmap3);
				// Marker marker = (Marker) mBaiduMap.addOverlay(option);
				break;
			}
		}
	}

	public void setMapMode(View view) {
		boolean checked = ((RadioButton) view).isChecked();
		switch (view.getId()) {
		case R.id.normal:
			if (checked)
				mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
			break;
		case R.id.satellite:
			if (checked)
				mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
			break;
		}
	}

	@Override
	protected void onDestroy() {
		mMapView.onDestroy();
		mMapView = null;
		super.onDestroy();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		SDKInitializer.setCoordType(CoordType.BD09LL); //百度地图SDK默认BD09LL坐标，百度定位SDK默认GCJ02坐标,切换地图需要重新设置,读取点时转换?
		//mMapView.onResume();
		mBaiduMap.clear();
		BitmapDescriptor bitmap4 = BitmapDescriptorFactory.fromResource(R.drawable.marker);
		OverlayOptions option = new MarkerOptions().position(new LatLng(0,0)).icon(bitmap4);
		marker1 = (Marker) mBaiduMap.addOverlay(option);

		Intent intent = getIntent();
		Log.e(Thread.currentThread().getStackTrace()[2] + "", intent.getExtras() + "");
		String action = intent.getAction();
		Log.e(Thread.currentThread().getStackTrace()[2] + "", action + "");
		if (intent.ACTION_VIEW.equals(action)) {
			Uri uri = intent.getData();
            //filepath = uri.toString();
            // QQ：content://com.tencent.mobileqq.fileprovider/external_files/storage/emulated/0/Android/data/com.tencent.mobileqq/Tencent/QQfile_recv/%E9%BD%90%E5%A4%A9%E5%B2%AD-%E8%B6%B3%E7%90%83%E8%AE%AD%E7%BB%83%E5%9F%BA%E5%9C%B0-%E5%8C%97%E6%B2%9F-%E7%99%BD%E7%80%91%E5%AF%BA-%E7%A2%BE%E6%88%BF%E6%B0%B4%E5%BA%93-%E9%9D%99%E5%BF%83%E5%B1%B1%E5%BA%84-%E9%AB%98%E5%B4%96%E5%8F%A3.gpx
            // 微信：content:/0@com.tencent.mm.external.fileprovider/external/Android/data/com.tencent.mm/MicroMsg/b7e2b82341dbb86b43fd19f9590f0577/attachment/content_1615190457891
            //filepath = uri.getEncodedPath();
            // QQ：/external_files/storage/emulated/0/Android/data/com.tencent.mobileqq/Tencent/QQfile_recv/%E9%BD%90%E5%A4%A9%E5%B2%AD-%E8%B6%B3%E7%90%83%E8%AE%AD%E7%BB%83%E5%9F%BA%E5%9C%B0-%E5%8C%97%E6%B2%9F-%E7%99%BD%E7%80%91%E5%AF%BA-%E7%A2%BE%E6%88%BF%E6%B0%B4%E5%BA%93-%E9%9D%99%E5%BF%83%E5%B1%B1%E5%BA%84-%E9%AB%98%E5%B4%96%E5%8F%A3.gpx
            // 微信：/external/Android/data/com.tencent.mm/MicroMsg/b7e2b82341dbb86b43fd19f9590f0577/attachment/content_1615190457891
            filepath = Uri.decode(uri.getEncodedPath());
            // QQ：/external_files/storage/emulated/0/Android/data/com.tencent.mobileqq/Tencent/QQfile_recv/齐天岭-足球训练基地-北沟-白瀑寺-碾房水库-静心山庄-高崖口.gpx
            // 微信：/external/Android/data/com.tencent.mm/MicroMsg/b7e2b82341dbb86b43fd19f9590f0577/attachment/content_1615190457891
            if (filepath.startsWith("/external_files/"))
                filepath = filepath.replace("/external_files/", "/");
            else if (filepath.startsWith("/external/"))
                filepath = filepath.replace("/external/", Environment.getExternalStorageDirectory().getPath() + "/");
            Log.e(Thread.currentThread().getStackTrace()[2] + "", filepath);
		} else {
			filename = intent.getStringExtra("filename");
			filepath = MainApplication.dir_gpx + filename;
		}
		track = new Track();
		track = RWXML.read1(filepath);

		DrawGPX();
		DrawPhoto();
	}

	@Override
	protected void onPause() {
		super.onPause();
		//mMapView.onPause();
		flag = true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, "分享");
		menu.add(0, 1, 1, "重命名");
		menu.add(0, 2, 2, "删除");
		menu.add(0, 3, 3, "退出");
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int item_id = item.getItemId();
		switch (item_id) {
		case 0:
			Intent intent = new Intent();
			intent.setAction(Intent.ACTION_SEND);
			intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(filepath)));
			intent.setType("*/*");
			startActivity(Intent.createChooser(intent, "分享 " + filename));
			break;
		case 1:
			if (!filepath.equals(MainApplication.wfp)) {
				final EditText editText = new EditText(HistoryLocus.this);
				editText.setText(filename);
				AlertDialog.Builder dialog = new AlertDialog.Builder(HistoryLocus.this);
				dialog.setTitle("重命名").setView(editText);
				dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						File file = new File(filepath);
						String path = filepath.substring(0, filepath.lastIndexOf("/"));
						String filename1 = editText.getText().toString();
						String filepath1 = path + File.separator + filename1;
						File file1 = new File(filepath1);
						if (file.renameTo(file1)) {
							Intent intent = getIntent();
							intent.putExtra("filename", filename1);
							startActivity(intent);
						} else {
							new AlertDialog.Builder(HistoryLocus.this).setIcon(android.R.drawable.stat_notify_error).setTitle("操作").setMessage("重命名失败\n" + filepath1).setPositiveButton("确定", null);
						}
					}
				});
				dialog.setNegativeButton("取消", null);
				dialog.show();
			} else {
				new AlertDialog.Builder(HistoryLocus.this).setIcon(R.drawable.warn).setTitle("操作").setMessage("此文件正在记录中，请先退出新行程！").setPositiveButton("确定", null);;
			}
			break;
		case 2:
			new AlertDialog.Builder(HistoryLocus.this).setIcon(R.drawable.warn).setTitle("删除操作").setMessage("此步骤不可还原，确定删除\n" + filepath + " ？")
					.setPositiveButton("是", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							String text;
							Log.e(Thread.currentThread().getStackTrace()[2] + "", MainApplication.wfp);
							if (!filepath.equals(MainApplication.wfp)) {
								File file = new File(filepath);
								if (file.delete()) {
									text = filepath + " 删除成功";
								} else {
									text = filepath + " 删除失败";
								}
								startActivity(new Intent(HistoryLocus.this, GPXList.class));
							} else {
								text = "此文件正在记录中，请先退出新行程！";
							}
							Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
						}
					}).setNegativeButton("否", null).show();
			break;
		case 3:
			finish();
			startActivity(new Intent(HistoryLocus.this, MenuActivity.class));
			break;
		}
		return true;
	}

	void DrawGPX() {
		num = track.points.size();
		//textView_info.setText(MainApplication.msg);
		textView_info.setText(track.info);
		mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().zoom(mBaiduMap.getMapStatus().zoom).build()));
		mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(track.points.get(num / 2)));
		if (num == 1) {
			track.points.add(track.points.get(0));
		}
		OverlayOptions ooPolyline = new PolylineOptions().width(4).color(0xA00000FF).points(track.points);
		mBaiduMap.addOverlay(ooPolyline);
		OverlayOptions option1 = new MarkerOptions().position(track.points.get(0)).icon(bitmap1);
		mBaiduMap.addOverlay(option1);
		OverlayOptions option2 = new MarkerOptions().position(track.points.get(num - 1)).icon(bitmap2);
		mBaiduMap.addOverlay(option2);
		imgbtn1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(track.points.get(num / 2)));
			}
		});
	}

	void DrawPhoto() {
		Date date = null;
		try {
			date = SDF.parse(track.starttime);
		} catch (Exception e) {
			Log.e(Thread.currentThread().getStackTrace()[2] + "", e.toString());
		}
		long ldate = date.getTime();
		long ldate1 = ldate + 24*60*60*1000;

		//query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
		String[] projection = new String[]{ MediaStore.Images.Media.DATA , MediaStore.Images.Media.DATE_TAKEN };
		String selection = MediaStore.Images.Media.DATE_TAKEN + ">=? and " + MediaStore.Images.Media.DATE_TAKEN + "<?";
		String[] selectionArgs =  new String[]{ String.valueOf(ldate), String.valueOf(ldate1) };
		Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, selection, selectionArgs, null);

		final List<String> list_image_path = new ArrayList<String>();
		final List<String> list_time = new ArrayList<String>();
		while (cursor.moveToNext()) {
			String imagePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
			long date_taken = cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media.DATE_TAKEN));
			date = new Date(date_taken);
			String stime = SDF.format(date);
			try {
				//EXIF的GPS数据转经纬度，https://blog.csdn.net/diyangxia/article/details/50995253
				ExifInterface exifInterface = new ExifInterface(imagePath);
				String latValue = exifInterface.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
				String lngValue = exifInterface.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
				String latRef = exifInterface.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF);
				String lngRef = exifInterface.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF);
				if (latValue != null && lngValue != null && latRef != null && lngRef != null) {
					LatLng latLng = new LatLng(rationalToDouble(latValue, latRef), rationalToDouble(lngValue, lngRef));
					CoordinateConverter converter = new CoordinateConverter();
					converter.from(CoordinateConverter.CoordType.GPS);
					converter.coord(latLng);
					latLng = converter.convert();
					list_photo_LatLng.add(latLng);
					list_image_path.add(imagePath);
					list_time.add(stime);
				}
			} catch (Exception e) {
				Log.e(Thread.currentThread().getStackTrace()[2] + "", e.toString());
			}
		}
		cursor.close();
		if (list_photo_LatLng.size() > 1) {
			for (int i = 0; i < list_photo_LatLng.size(); i++) {
				OverlayOptions options;
				Bundle bundle = new Bundle();
				bundle.putInt("index", i);
				bundle.putString("time", list_time.get(i));
				bundle.putString("image_path", list_image_path.get(i));
				options = new MarkerOptions().position(list_photo_LatLng.get(i)).icon(bitmap3).extraInfo(bundle);
				mBaiduMap.addOverlay(options);
			}
		}
	}

	double rationalToDouble(String rational, String ref) {
		String[] parts = rational.split(",");
		String[] pair;
		pair = parts[0].split("/");
		double degrees = Double.parseDouble(pair[0].trim()) / Double.parseDouble(pair[1].trim());
		pair = parts[1].split("/");
		double minutes = Double.parseDouble(pair[0].trim()) / Double.parseDouble(pair[1].trim());
		pair = parts[2].split("/");
		double seconds = Double.parseDouble(pair[0].trim()) / Double.parseDouble(pair[1].trim());
		double result = degrees + (minutes / 60.0) + (seconds / 3600.0);
		if ((ref.equals("S") || ref.equals("W"))) {
			return -result;
		}
		return result;
	}

	public class MyThread implements Runnable {
		int i = 0;

		int geti() {
			return i;
		}

		@Override
		public void run() {
			while (!flag) {
				if (i < num) {
					OverlayOptions option = new MarkerOptions().position(track.points.get(i)).icon(bitmap3);
					Marker marker = (Marker) mBaiduMap.addOverlay(option);
					try {
						Thread.sleep(100);
					} catch (Exception e) {
						Log.e(Thread.currentThread().getStackTrace()[2] + "", e.toString());
					}
					i++;
					if (!flag)
						marker.remove();
				}
			}
		}
	}

}